package com.epoint.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class RedisRest {

    @Autowired
    RedisTemplate redisTemplate;

    private final static String REDIS_KEY = "MENU";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/testredis")
    public JSONObject testRedis(@RequestParam("params") String paramsStr) {
        JSONObject params = JSONObject.parseObject(paramsStr);

        JSONObject result = new JSONObject();
        JSONObject custom = new JSONObject();

        HashOperations hashOperations = stringRedisTemplate.opsForHash();

        JSONArray userMenus = null;
        if(params.containsKey("name") && !StringUtils.isEmpty(params.getString("name"))){
            String userMenuStr = (String) hashOperations.get(REDIS_KEY, params.getString("name"));

            if(StringUtils.isEmpty(userMenuStr)){
                userMenus = new JSONArray();
            }
            else{
                userMenus = JSONObject.parseArray(userMenuStr);
            }
            userMenus.add(params.getString("menu"));
            hashOperations.put(REDIS_KEY, params.getString("name"), userMenus.toJSONString());
        }

        custom.put("redisdata", userMenus == null ? "" : userMenus.toJSONString());
        result.put("status", "200");
        result.put("custom", custom);
        return result;
    }



}
